package com.briup.web.controller;

import com.briup.pojo.User;
import com.briup.pojo.dto.UserBaseDto;
import com.briup.pojo.dto.UserPageDto;
import com.briup.pojo.vo.UserPageVO;
import com.briup.response.Result;
import com.briup.service.UserService;
import com.briup.utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api(tags = "用户管理模块接口")
@RestController
@RequestMapping("/users")
public class UserController {

	@Resource
	private UserService userService;

	// 新增方法：登陆时该方法必须保留
	@ApiOperation("传入token，获取用户id")
	@GetMapping("/getUserInfo")
	public Result getUserInfo(HttpServletRequest request){
		String token = request.getHeader("token");
		Integer userId = JwtUtil.getUserId(token);
		User user = userService.getUserById(userId);
		return Result.success(user);
	}

	@ApiOperation("分页多条件查询用户信息")
	@GetMapping
	public Result<PageInfo<UserPageVO>> list(HttpServletRequest request,UserPageDto userPageDto) {
		//先校验是否登陆过
		String token = request.getHeader("token");
		JwtUtil.parseJWT(token);
		log.info("分页多条件查询用户数据:{}", userPageDto);
		return Result.success(userService.getUsersPageByConditional(userPageDto));
	}

	@ApiOperation("删除用户")
	@DeleteMapping("/{ids}")
	public Result<String> deleteUsers(@PathVariable("ids") List<Integer> ids) {
		log.info("删除用户:{}", ids);
		userService.deleteUsers(ids);
		return Result.success();
	}

	@ApiOperation("新增用户")
	@PostMapping
	public Result<String> addUser(@RequestBody UserBaseDto userBaseDto) {
		log.info("开始新增用户:{}", userBaseDto);
		userService.addUser(userBaseDto);
		return Result.success();
	}

	@ApiOperation("获取用户信息")
	@GetMapping("/{id}")
	public Result<User> getUserInfo(@PathVariable("id") Integer id) {
		log.info("获取{}号用户的信息:", id);
		return Result.success(userService.getUserById(id));
	}

	@ApiOperation("修改用户")
	@PutMapping
	public Result<String> updateUser(@RequestBody UserBaseDto userBaseDto) {
		log.info("开始修改用户信息:{}", userBaseDto);
		userService.updateUser(userBaseDto);
		return Result.success();
	}

}
